from django.shortcuts import render
from django.http import FileResponse, HttpResponse
from config import Config
import os


def theconomist(request, *args):
    now_path = request.path.strip('/')
    local_path = os.path.join(Config.TEMPLATE, now_path)
    if os.path.isdir(local_path):
        sort_list = sorted(os.listdir(local_path))
        if 'images' in sort_list:
            sort_list.remove('images')
        if '.git' in sort_list:
            sort_list.remove('.git')
        if 'economist.json' in sort_list:
            sort_list.remove('economist.json')
        if 'cover.jpg' in sort_list:
            sort_list.remove('cover.jpg')
        context = {'now_path': now_path, 'dir_content': sort_list}
        return render(request, 'theconomist/path.html', context)
    else:
        if local_path.endswith('.md'):
            md = open(local_path, mode='r').read()
            md.replace('>', '&gt;')
            return render(request, 'theconomist/markdown.html', {'md': md.replace('\n', '\\n').replace('images/', '../images/')})
        sending = open(local_path, mode='rb')
        return FileResponse(sending)
